package org.pizza.did.autoconfigure;

import org.pizza.did.api.WorkerIdDistributor;
import org.pizza.did.properties.IdProperties;
import org.pizza.didi.redis.RedisDistributor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author 高巍
 * @since  2020/10/13 3:40 下午
 */
@Configuration(
        proxyBeanMethods = false
)
@EnableConfigurationProperties({IdProperties.class})
public class RedisDistributorConfiguration implements EnvironmentAware {

    private static final Logger log = LoggerFactory.getLogger(ZookeeperDistributorConfiguration.class);
    private final IdProperties idProperties;
    private Environment environment;

    public RedisDistributorConfiguration(IdProperties idProperties) {
        this.idProperties = idProperties;
    }

    @Bean
    @ConditionalOnMissingBean({WorkerIdDistributor.class})
    @ConditionalOnProperty(prefix = "did.redis", name = {"enabled"}, havingValue = "true", matchIfMissing = false)
    RedisDistributor workerIdDistributor(StringRedisTemplate stringRedisTemplate) {
        String ip = this.environment.getProperty("spring.cloud.client.ip-address");
        RedisDistributor distributor = new RedisDistributor(this.idProperties.getName(), ip, String.valueOf(this.idProperties.getRedis().getPort()), this.idProperties.getMaxWorkId(),stringRedisTemplate);
        boolean init = distributor.init();
        if (!init) {
            log.error("IdGenerator RedisDistributor  initialized  workId failed");
        }
        return distributor;
    }

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
